//
//  BRMSwitchUIView.m
//  BrezzeSaaS
//
//  Created by macos on 14.3.22.
//  Copyright © 2022 Brezze GWG. All rights reserved.
//

#import "BRMSwitchUIView.h"

@interface BRMSwitchUIView ()
{
    UIView *_itemView;
    CGFloat _item_w;
}


@end

@implementation BRMSwitchUIView

- (instancetype)initWithCoder:(NSCoder *)coder
{
    self = [super initWithCoder:coder];
    if (self) {
        [self setUI];
    }
    return self;
}

- (instancetype)init
{
    self = [super init];
    if (self) {
        [self setUI];
    }
    return self;
}

- (void)itemClick:(UIButton *)btn {
    
    self.isOn = !self.isOn;
    
    if (self.switchClickBlock) {
        self.switchClickBlock(self.isOn);
    }
}

- (void)setIsOn:(BOOL)isOn {
    _isOn = isOn;
    [self layoutIfNeeded];
    [UIView animateWithDuration:0.35 animations:^{
        if (!isOn) {
            self->_itemView.transform = CGAffineTransformMakeRotation(0);
            self.backgroundColor = UIColorMake(210, 216, 226);
        }else {
            CGFloat w = self.mj_w - self.mj_h;
            self->_itemView.transform = CGAffineTransformMakeTranslation(w, 0);
            self.backgroundColor = kColorMain;
        }
        
    }];
    
}


- (void)setSwitchViewColor:(UIColor *)switchViewColor {
    _switchViewColor = switchViewColor;
    _itemView.backgroundColor = switchViewColor;
}

#pragma mark - UI --
- (void)setUI {
    if (self.mj_w == 0) {
        self.frame = CGRectMake(0, 0, 44, 24);
    }
    self.backgroundColor  = UIColorMake(210, 216, 226);
    self.layer.cornerRadius = self.mj_h / 2.0;
    self.layer.masksToBounds = YES;
    _item_w = self.mj_w - 4 ;
    UIView *swView = [[UIView alloc] initWithFrame:CGRectMake(2, 2, self.mj_h - 4, self.mj_h - 4)];
    swView.layer.cornerRadius = (self.mj_h - 6)/ 2.0;
    swView.layer.masksToBounds = YES;
    swView.backgroundColor = kUIColorMainTint;
    [self addSubview:swView];
    _itemView = swView;
    
    UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
    [btn setTitle:@"" forState:UIControlStateNormal];
    btn.frame = self.bounds;
    [self addSubview:btn];
    [btn addTarget:self action:@selector(itemClick:) forControlEvents:UIControlEventTouchUpInside];
}

/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    // Drawing code
}
*/

@end
